package com.example.demo.controller;

import com.example.demo.dto.DataSourceConfigDTO;
import com.example.demo.dto.QueryResultDTO;
import com.example.demo.entity.DataSourceConfig;
import com.example.demo.request.CreateDataSourceConfigRequest;
import com.example.demo.request.ExecuteQueryRequest;
import com.example.demo.request.ExecuteQueryWithParamsRequest;
import com.example.demo.request.GetDataSourceConfigByNameRequest;
import com.example.demo.request.TestConnectionRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.dto.PageExtra;
import com.example.demo.service.DataSourceConfigService;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/datasource-configs")
public class DataSourceConfigController {

    @Autowired
    private DataSourceConfigService dataSourceConfigService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<DataSourceConfigDTO>>> getDataSourceConfigs(
            @RequestParam(defaultValue = "0") int page,
           @RequestParam(defaultValue = "10") int size,
           @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String dbType,
            HttpServletRequest request) {

        List<DataSourceConfigDTO> configs;
        long total;

        if (status != null) {
            configs = dataSourceConfigService.getDataSourceConfigsByStatus(status, page, size);
            total = dataSourceConfigService.countDataSourceConfigsByStatus(status);
        } else if (dbType != null) {
            configs = dataSourceConfigService.getDataSourceConfigsByDbType(dbType, page, size);
            total = dataSourceConfigService.countDataSourceConfigsByDbType(dbType);
        } else {
            configs = dataSourceConfigService.getDataSourceConfigs(page, size);
            total = dataSourceConfigService.countDataSourceConfigs();
        }

        PageExtra extra = new PageExtra(page, size, total);

        return ResponseEntity.ok(
                ApiResponse.success(configs, "请求成功", request.getRequestURI(), extra));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<DataSourceConfigDTO>> getDataSourceConfig(
            @PathVariable Long id,
            HttpServletRequest request) {

        DataSourceConfigDTO config = dataSourceConfigService.getDataSourceConfigById(id);
        return ResponseEntity.ok(
                ApiResponse.success(config, "查询成功", request.getRequestURI(), null));
    }

    @PostMapping("/by-name")
    public ResponseEntity<ApiResponse<DataSourceConfigDTO>> getDataSourceConfigByName(
            @Valid @RequestBody GetDataSourceConfigByNameRequest request,
            HttpServletRequest requestObj) {

        DataSourceConfigDTO config = dataSourceConfigService.getDataSourceConfigByName(request.getName());
        return ResponseEntity.ok(
                ApiResponse.success(config, "查询成功", requestObj.getRequestURI(), null));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<DataSourceConfig>> createDataSourceConfig(
            @Valid @RequestBody CreateDataSourceConfigRequest request,
            HttpServletRequest requestObj) {

        DataSourceConfig config = dataSourceConfigService.createDataSourceConfig(request);
        return ResponseEntity.ok(
                ApiResponse.success(config, "数据源配置创建成功", requestObj.getRequestURI(), null));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> updateDataSourceConfig(
            @PathVariable Long id,  
            @Valid @RequestBody CreateDataSourceConfigRequest request,
            HttpServletRequest requestObj) {

        dataSourceConfigService.updateDataSourceConfig(id, request);
        return ResponseEntity.ok(
                ApiResponse.success(null, "数据源配置更新成功", requestObj.getRequestURI(), null));
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteDataSourceConfig(
            @PathVariable Long id,
            HttpServletRequest requestObj) {

        dataSourceConfigService.deleteDataSourceConfig(id);
        return ResponseEntity.ok(
                ApiResponse.success(null, "数据源配置删除成功", requestObj.getRequestURI(), null));
    }

    @PostMapping("/{id}/test-connection")
    public ResponseEntity<ApiResponse<Boolean>> testConnection(
             @PathVariable Long id,
            HttpServletRequest request) {

        boolean isConnected = dataSourceConfigService.testConnection(id);
        String message = isConnected ? "连接测试成功" : "连接测试失败";

        return ResponseEntity.ok(
                ApiResponse.success(isConnected, message, request.getRequestURI(), null));
    }

    @PostMapping("/test-connection-with-params")
    public ResponseEntity<ApiResponse<Boolean>> testConnectionWithParams(
            @Valid @RequestBody TestConnectionRequest request,
            HttpServletRequest requestObj) {

        boolean isConnected = dataSourceConfigService.testConnectionWithParams(request);
        String message = isConnected ? "连接测试成功" : "连接测试失败";

        return ResponseEntity.ok(
                ApiResponse.success(isConnected, message, requestObj.getRequestURI(), null));
    }

    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            HttpServletRequest requestObj) {

        dataSourceConfigService.updateStatus(id, status);
        String message = status == 1 ? "数据源配置已启用" : "数据源配置已禁用";

        return ResponseEntity.ok(
                ApiResponse.success(null, message, requestObj.getRequestURI(), null));
    }

    @PostMapping("/{id}/execute-query")
    public ResponseEntity<ApiResponse<QueryResultDTO>> executeQuery(
            @PathVariable Long id,
            @Valid @RequestBody ExecuteQueryRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceConfigService.executeQuery(id, request);
        return ResponseEntity.ok(
                ApiResponse.success(result, "查询执行成功", requestObj.getRequestURI(), null));
    }

    @PostMapping("/execute-query-with-params")
    public ResponseEntity<ApiResponse<QueryResultDTO>> executeQueryWithParams(
            @Valid @RequestBody ExecuteQueryWithParamsRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceConfigService.executeQueryWithParams(request);
        return ResponseEntity.ok(
                ApiResponse.success(result, "查询执行成功", requestObj.getRequestURI(), null));
    }

    @GetMapping("/{id}/table-info/{tableName}")
    public ResponseEntity<ApiResponse<QueryResultDTO>> getTableInfoAndSampleData(
            @PathVariable Long id,
            @PathVariable String tableName,
            HttpServletRequest request) {

        QueryResultDTO result = dataSourceConfigService.getTableInfoAndSampleData(id, tableName);
        return ResponseEntity.ok(
                ApiResponse.success(result, "表信息获取成功", request.getRequestURI(), null));
    }


    @PostMapping("/table-info/{tableName}")
    public ResponseEntity<ApiResponse<QueryResultDTO>> getTableInfoAndSampleDataWithParams(
             @PathVariable String tableName,
            @Valid @RequestBody TestConnectionRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceConfigService.getTableInfoAndSampleDataWithParams(request, tableName);
        return ResponseEntity.ok(
                ApiResponse.success(result, "表信息获取成功", requestObj.getRequestURI(), null));
    }
}